import pymysql


class DBUtil:
    def __init__(self, host, user, password, database, port=3306, charset='utf8'):
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.port = port
        self.charset = charset

    def update(self, sql, params=None):
        try:
            db = pymysql.connect(
                host=self.host,
                user=self.user,
                password=self.password,
                database=self.database,
                port=self.port,
                charset=self.charset
            )
            cursor = db.cursor()
            cursor.execute(sql, params)
            db.commit()
            print('数据操作成功')
        except Exception as e:
            print('数据操作失败', e)
        finally:
            cursor.close()
            db.close()


    def select(self, sql, params=None):
        try:
            db = pymysql.connect(
                host=self.host,
                user=self.user,
                password=self.password,
                database=self.database,
                port=self.port,
                charset=self.charset
            )
            cursor = db.cursor()
            cursor.execute(sql, params)
            data = cursor.fetchall()
            return data
        except Exception as e:
            print('数据查询失败', e)
        finally:
            cursor.close()
            db.close()

#if __name__ == "__main__": 这句话就是作为一个条件限制，这句话以下的代码只有在运行的这个.py文件的时候才会执行，
# 当作为模块在别的.py文件中调用的时候，本.py文件中这句话下面的代码不会执行。
if __name__ == '__main__':
    d = DBUtil('localhost', 'root', '123456', 'testCase.py')
    sql0 = 'select * from user'
    data0 = d.select(sql0)
    for i in data0:
        print(i)
